package at.hockey.ticker;

import java.util.ListIterator;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;


public class HockeyTickerUI extends Activity implements OnTouchListener {

	static final String SEND_GAME_NOTIFICATIONS = "at.hockey.ticker.SEND_GAME_NOTIFICATIONS";
	static final String SEND_SVCSTAT_NOTIFICATIONS = "at.hockey.ticker.SEND_SVCSTAT_NOTIFICATIONS";
	private final String TAG = this.getClass().getSimpleName();

	Button mButtonStart, mButtonStop;
	TextView mTVServiceStatus, mTVDataStatus;	

	// App Vars
	HTApplication HTapp;
	HTReceiverDat mReceiverDat;
	HTReceiverStat mReceiverStat;
	
	IntentFilter filterDat, filterStat;
	
	public String mDataBoxData;
	public String mServiceStatus;	
	

	
	private GestureDetector mGestureDetector; 
	private ViewFlipper mVF;


	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i(TAG, "begin oncreate");
        // incl

        //set main xml layout
        setContentView(R.layout.main);        
        
        
        mButtonStart = (Button) findViewById(R.id.buttonStart);
        mButtonStop = (Button) findViewById(R.id.buttonStop);
        
        mButtonStart.setOnClickListener(mButtonHandler); 
        mButtonStop.setOnClickListener(mButtonHandler);
        
        mTVServiceStatus = (TextView) findViewById(R.id.serviceStatusId);
        mTVDataStatus = (TextView) findViewById(R.id.dataStatusId);
        
        HTapp = (HTApplication) getApplication();
        
        mReceiverDat = new HTReceiverDat();
        mReceiverStat = new HTReceiverStat();
        
        filterDat = new IntentFilter( HTService.NEW_STATUS_INTENT );
        filterStat = new IntentFilter( HTService.NEW_SVCSTAT_INTENT );
 
        
        this.mVF = (ViewFlipper) this.findViewById(R.id.main_vf);

        //test
		//TODO generate data objects with real data
		generateTestData();
		
		//initially build ui hierarchy
        this.mGestureDetector = new GestureDetector(new OnFlingGestureListener(this));
		
		if(MatchOverview.getInstance() != null){	// TODO
		
			this.mVF.addView(new MatchOverviewUI(this));
			this.mVF.getChildAt(0).findViewById(R.id.mo_details_sv).setOnTouchListener(this);
			// TODO listener auf VF?
			
	        ListIterator<MatchDetails> itr = MatchOverview.getInstance().getMatchDetails().listIterator();
		    while(itr.hasNext()){
		    	
		    	MatchDetailsUI mdui = new MatchDetailsUI(this, itr.next());
		    	this.mVF.addView(mdui);
		    	mdui.findViewById(R.id.md_entries_sv).setOnTouchListener(this);
		    	// TODO listener auf VF?
		    }

	    }
        setAppTitle();
    }
    
	@Override
	public boolean onTouch(View v, MotionEvent e) {

		return this.mGestureDetector.onTouchEvent(e);
	}
	
	public void setAppTitle(){
		if(this.mVF.getDisplayedChild() == 0){
			this.setTitle("HT > Matches");
		}
		else{
			MatchDetailsUI mdui = (MatchDetailsUI) this.mVF.getChildAt(this.mVF.getDisplayedChild());
			MatchDetails md = mdui.getMatchDetails(); 
			String matchup = md.getTeam1() + " " + md.getScore() + " " + md.getTeam2();

			this.setTitle("HT > Match " + this.mVF.getDisplayedChild() + "/" + (this.mVF.getChildCount() - 1) + " > " + matchup);						
		}
	}

	
	
// incl
	
    @Override
    protected void onRestart() {
    super.onRestart();
    // Notification that the activity will be started
    Log.i(TAG, "onRestart");
    }

    @Override
    protected void onStart() {
    super.onStart();
    // Notification that the activity is starting
    Log.i(TAG, "onStart");
    }
    
    
    protected void onResume() {
        super.onResume();

        Log.i(TAG, "Activity.onResume");
        // Get Data from DataBox via Application
        this.setupData(); 
        this.setupSVCStatus();
        
        super.registerReceiver(mReceiverDat, filterDat,SEND_GAME_NOTIFICATIONS, null);
        super.registerReceiver(mReceiverStat, filterStat,SEND_SVCSTAT_NOTIFICATIONS, null);
        
        Log.i(TAG, "Activity.onResume - setupList() done");
    }
    
    private void setupData() {
    	mDataBoxData = HTapp.fetchData();
        mTVDataStatus.setText(mDataBoxData);
        Log.i(TAG, "setupData() done");
    }    
    
    private void setupSVCStatus() { 
        // HTapp.isServiceRunning() = false - in onDestroy set to false
        mServiceStatus = (HTapp.isServiceRunning()) ? "SVC running" : "SVC NOT running";
        mTVServiceStatus.setText(mServiceStatus);
        Log.i(TAG, "setupSVCStatus() done");
    }    
    
 // Receiver to wake up when UpdaterService gets a new status
 // It refreshes the Activity list 
    class HTReceiverDat extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
        setupData();
        setupSVCStatus();
        Toast.makeText(HockeyTickerUI.this, "New data arrived", Toast.LENGTH_LONG).show();
        Log.i("HTReceiverDat", "ReceiverDaten.onReceived: setupData() done");
      }
    }
    
    // Receiver to wake up when UpdaterService gets a new status
    // It refreshes the Activity list 
       class HTReceiverStat extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
        	 setupSVCStatus();
        	 Log.i("HTReceiverStat", "ReceiverStatus.onReceived: setText() done");
         }
       }
    
    
    protected void onPause() {
        super.onPause();
        // UNregister the receiver
        unregisterReceiver(mReceiverDat);
        unregisterReceiver(mReceiverStat);
        Log.i(TAG, "onPause");
      }

   
    @Override
    protected void onDestroy() {
	    Log.i(TAG, "onDestroy");
    	super.onDestroy();
    }	
	

		
	//test
	private void generateTestData() {
	
		MatchOverview mo = new MatchOverview();
    
	    MatchDetails md = new MatchDetails("30.03.2012", "RBS", "FAV", "Period 2", "Last Action RBS: GK ON", "Last Action FAV: 2 Min.");
	    md.addMatchDetailsEntry(new MatchDetailsEntry(1, "RBS", "GK ON", "00:00", "38 - DIVIS Reinhard"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(1, "FAV", "GK ON", "00:00", "01 - PINTARIC Matija"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(1, "FAV", "2 Min.", "06:29 - 08:29", "4 - CVETEK Igor (Hooking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(1, "RBS", "EQ", "1:0", "36 - PEWAL Marco"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "RBS", "EQ", "2:0", "89 - BRUCKER Marco"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "RBS", "2 Min.", "32:09 - 34:09", "18 - BOIS Daniel (Roughing)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "FAV", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    
	    mo.addMatchDetails(md);
	    
	    md = new MatchDetails("30.03.2012", "XXX", "YYY", "Period 1", "Last Action XXX: 2 Min.", "Last Action YYY: 0:1");
	    md.addMatchDetailsEntry(new MatchDetailsEntry(1, "XXX", "GK ON", "00:00", "38 - DIVIS Reinhard"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(1, "XXX", "2 Min.", "06:29 - 08:29", "4 - CVETEK Igor (Hooking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "YYY", "EQ", "2:0", "89 - BRUCKER Marco"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "XXX", "EQ", "2:1", "18 - BOIS Daniel (Roughing)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(3, "XXX", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(3, "LZG", "2 Min.", "37:28 - 39:28", "Lany roxx!"));

	    mo.addMatchDetails(md); 

	    md = new MatchDetails("01.04.2012", "RBS", "XXX", "Period 1", "Last Action XXX: 2 Min.", "Last Action YYY: 0:1");
	    md.addMatchDetailsEntry(new MatchDetailsEntry(1, "RBS", "GK ON", "00:00", "38 - DIVIS Reinhard"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(1, "XXX", "GK ON", "00:00", "38 - DIVIS Reinhard"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "RBS", "EQ", "1:0", "89 - BRUCKER Marco"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "RBS", "EQ", "2:0", "18 - BOIS Daniel (Roughing)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(2, "RBS", "EQ", "3:0", "18 - BOIS Daniel (Roughing)"));
	    md.addMatchDetailsEntry(new MatchDetailsEntry(3, "XXX", "2 Min.", "37:28 - 39:28", "23 - DERVARIC Damjan (High Sticking)"));
	    
	    mo.addMatchDetails(md); 
	}

	
	// Create an anonymous implementation of OnClickListener
	private OnClickListener mButtonHandler = new OnClickListener() {
		public void onClick(View v) {
	    	switch (v.getId()) {
	        case R.id.buttonStart:
	          Log.d(TAG, "onClick: starting service");
	          if (HTapp.isServiceRunning()) {
	        	  Toast.makeText(HockeyTickerUI.this, "Service already running", Toast.LENGTH_LONG).show();
	              Log.i(TAG, "Service already running");
	              // stopService(new Intent(this, HTService.class));
	            } else {
	              startService(new Intent(HockeyTickerUI.this, HTService.class));
	              Log.i(TAG, "Starting Service");
	              Toast.makeText(HockeyTickerUI.this, "Starting Service", Toast.LENGTH_LONG).show();
	            }          
	          // TODO Service Aufruf
	          break;
	        case R.id.buttonStop:
	          Log.d(TAG, "onClick: stopping service");
	          if (HTapp.isServiceRunning()) {
	        	stopService(new Intent(HockeyTickerUI.this, HTService.class));
	        	Toast.makeText(HockeyTickerUI.this, "Service stopped", Toast.LENGTH_LONG).show();
	            Log.i(TAG, "Stopping Service");
	          } else {
	          	  Toast.makeText(HockeyTickerUI.this, "No service running", Toast.LENGTH_LONG).show();
	          	  Log.i(TAG, "No service running");
	            }
	          // TODO Service Destroy
	          break;
	        }
	    }
	};
	
	
}




